package com.token.iot.bratterycharging.gateway.business;

import java.util.Date;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.outstanding.framework.base.SpringContextHolder;
import com.outstanding.framework.base.mq.MQProducer;
import com.outstanding.framework.core.Logger;
import com.outstanding.framework.core.PendingException;
import com.outstanding.framework.core.TransactionContext;
import com.outstanding.framework.log.LoggerFactory;
import com.token.iot.bratterycharging.gateway.AbstractOper;
import com.token.iot.bratterycharging.gateway.IDGeneration;
import com.token.iot.bratterycharging.gateway.IMEI;
import com.token.iot.bratterycharging.gateway.Oper;
import com.token.iot.bratterycharging.gateway.api.Constant;
import com.token.iot.bratterycharging.gateway.api.LocalFee;

import io.netty.channel.ChannelHandlerContext;


/**
 * 线下投币消费上报
 * @author chenzhixuan
 *
 */
@Component("UTBOper")
public class UTBOper extends AbstractOper{
	
	
	
	private static Logger loger = LoggerFactory.getLogger("transactionLogger");
	
	@Autowired
	private MQProducer mQProducer;
	
	@Override
	public int onCall(byte[] b,ChannelHandlerContext ctx) throws PendingException {
		String val = new String(b);
		loger.info(" the UTB response =" + val);
		String imei = IMEI.getIMEI(ctx);
		String sessionid = IDGeneration.getSessionID(b);
		String  left = val.substring(14);
		String[] params = left.split("#/#");
		LocalFee lf = new LocalFee();
		lf.setImei(imei);
		lf.setFeeType(10);
		lf.setTime(new Date());
		
		try {
			//投币数量
			int amount = Integer.parseInt(params[0]);
			int index =Integer.parseInt(params[1]);
			lf.setAmount(amount);
			lf.setPort(index);
		}catch(Exception e) {
			loger.error(e);
		}
		Gson gs = new Gson();
		String str = gs.toJson(lf);
		
		
		mQProducer.sendMessageByQueue(Constant.MESSAGEHEAD+Constant.QueueOfflinePayed, str);
		String last = params[2];
		HashMap<String,String> map = new HashMap();
		map.put("NO", last);
		TransactionContext.putData(Constant.PARAMS, map);
		TransactionContext.putData(Constant.SENDER, "DLB");
		
		return 1;
	}

}
